#include "translatoragentwindow.h"
#include "loadinganimation.h"
#include "screenshotoverlay.h"

#include <QFrame>
#include <QVBoxLayout>
#include <QWidget>
#include <QHBoxLayout>
#include <QPushButton>
#include <QLabel>
#include <QSpacerItem>
#include <QSizePolicy>
#include <QMouseEvent>
#include <QRect>
#include <QTimer>
#include <QStackedWidget>
#include <QWebEngineView>
#include <QBuffer>

#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QHttpMultiPart>
#include <QHttpPart>
#include <QJsonDocument>
#include <QJsonObject>
#include <QTimer>
#include <QScreen>
#include <QApplication>
#include <QStandardPaths>
#include <QWindow>

// #include <QtSvgWidgets/QSvgWidget>      //显示svg图标


TranslatorAgentWindow::TranslatorAgentWindow(QWidget *parent)
    : QMainWindow(parent),m_isPinned(true)
{
    // //启动p2t serve
    // m_p2tProcess = new QProcess(this);

    // // 1. 找到 conda.exe 的路径
    // //    通常在 anaconda3/Scripts/conda.exe
    // //    我们需要找到 Anaconda 的安装目录
    // QString condaPath = "D:/anaconda3/Scripts/conda.exe";

    // // 2. 准备 conda run 的所有参数
    // QStringList arguments;
    // arguments << "run"
    //           << "-n" << "p2t_env" // 指定 conda 环境名
    //           << "--no-capture-output" // 【重要】让后台服务的日志能实时打印出来
    //           << "p2t" << "serve" << "-p" << "8503";

    // qDebug() << "准备启动后台服务:" << condaPath << arguments.join(" ");

    // // 3. 启动进程
    // m_p2tProcess->start(condaPath, arguments);

    // // 4. （可选但推荐）连接信号，以便在Qt的输出窗口看到后台日志
    // connect(m_p2tProcess, &QProcess::readyReadStandardOutput, this, [this](){
    //     qDebug() << "[p2t_server_stdout]:" << m_p2tProcess->readAllStandardOutput();
    // });
    // connect(m_p2tProcess, &QProcess::readyReadStandardError, this, [this](){
    //     qDebug() << "[p2t_server_stderr]:" << m_p2tProcess->readAllStandardError();
    // });



    m_aiSocket = new QTcpSocket(this);
    qDebug() << "正在尝试连接到AI服务 (127.0.0.1:8504)...";
    m_aiSocket->connectToHost("127.0.0.1", 8504);

    // 如下是UI
    setWindowFlags(Qt::FramelessWindowHint | Qt::Tool |Qt::WindowStaysOnTopHint);
    setAttribute(Qt::WA_TranslucentBackground);
    resize(400, 225);
    setMinimumSize(400,225);
    setMouseTracking(true);

    // m_contentView->setAttribute(Qt::WA_TransparentForMouseEvents);

    // --- 创建主UI容器和布局 ---
    m_centralWidget = new QFrame(this);
    m_centralWidget->setObjectName("centralWidget");
    m_mainLayout = new QVBoxLayout(m_centralWidget);
    m_mainLayout->setContentsMargins(0, 0, 0, 0);
    m_mainLayout->setSpacing(0);
    setCentralWidget(m_centralWidget); // 将我们的画板设置为主控件

    // --- 创建工具栏 ---
    m_toolbar = new QWidget();
    m_toolbar->setObjectName("toolbar");
    m_toolbar->setFixedHeight(45);
    QHBoxLayout *toolbarLayout = new QHBoxLayout(m_toolbar);
    toolbarLayout->setContentsMargins(10, 0, 10, 0);
    toolbarLayout->setSpacing(10);

    // --- "新对话"按钮 ---
    m_newChatButton = new QPushButton("新对话",m_toolbar);
    m_newChatButton->setObjectName("toolbarButton");
    m_newChatButton->setCursor(Qt::PointingHandCursor);
    m_newChatButton->setToolTip("新对话");

    // 创建一个水平布局，把图标和文字放进按钮里
    QHBoxLayout *newChatLayout = new QHBoxLayout(m_newChatButton);
    newChatLayout->setContentsMargins(4, 0, 8, 0); // 微调内边距
    newChatLayout->setSpacing(6);                  // 图标和文字的间距

    // --- "截图"按钮 ---
    m_screenshotButton = new QPushButton("截图翻译",m_toolbar);
    m_screenshotButton->setObjectName("toolbarButton");
    m_screenshotButton->setCursor(Qt::PointingHandCursor);
    m_screenshotButton->setToolTip("截图翻译");

    // --- "置顶"按钮 ---
    m_pinButton = new QPushButton(m_toolbar);
    m_pinButton->setObjectName("toolbarButton");
    m_pinButton->setCursor(Qt::PointingHandCursor);

    updatePinStatus();

    // --- 将按钮和弹簧添加到工具栏布局 ---
    QSpacerItem *spacer = new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum);
    toolbarLayout->addWidget(m_newChatButton);
    toolbarLayout->addWidget(m_screenshotButton); // 将新创建的截图按钮添加到工具栏
    toolbarLayout->addSpacerItem(spacer);
    toolbarLayout->addWidget(m_pinButton);

    // --- 将工具栏和内容区域依次添加到主布局 ---
    m_mainLayout->addWidget(m_toolbar);         // 先添加工具栏

    m_stackedWidget = new QStackedWidget(this);
    m_contentView = new QWebEngineView(m_stackedWidget);
    // 对两个视图都进行相同的初始设置
    auto setupView = [this](QWebEngineView *view) {
        view->page()->setBackgroundColor(Qt::transparent);

        // 当页面加载完成时...
        connect(view, &QWebEngineView::loadFinished, this, [view](bool ok)
        {
            if (ok)
            {
                // 将JS脚本的执行推迟到下一个事件循环，确保DOM已就绪
                QTimer::singleShot(0, view, [view](){
                    // 定义滚动条的CSS样式
                    QString css = R"(
                        ::-webkit-scrollbar {
                            width: 8px; height: 8px;
                        }
                        ::-webkit-scrollbar-track {
                            background: transparent;
                        }
                        ::-webkit-scrollbar-thumb {
                            background: #555; border-radius: 4px;
                        }
                        ::-webkit-scrollbar-thumb:hover {
                            background: #777;
                        }
                    )";

                    // 准备JS注入脚本
                    QString script = QString(R"(
                        var style = document.createElement('style');
                        style.type = 'text/css';
                        style.innerHTML = `%1`;
                        document.head.appendChild(style);
                    )").arg(css.replace("\n", ""));

                    // 在信号的发送者 view 上执行脚本
                    view->page()->runJavaScript(script);
                });
            }
        });

        view->setHtml("<h3 style='color: #ccc; text-align: center;'>翻译结果将显示在这里...</h3>");
    };
    setupView(m_contentView);

    m_loadingWidget = new LoadingAnimation(m_stackedWidget);

    m_stackedWidget->addWidget(m_contentView);
    m_stackedWidget->addWidget(m_loadingWidget);

    m_stackedWidget->setCurrentWidget(m_contentView);

    m_mainLayout->addWidget(m_stackedWidget); // 再添加内容区域，它会自动填满剩余空间

    // 因为现在 m_stackedWidget 会自动伸展，不再需要弹簧来推挤。

    // 新建快捷键
    this->m_hotkey = new QHotkey(QKeySequence("Ctrl+Alt+S"), true, this);

    // 检查快捷键是否注册成功
    if (!m_hotkey->isRegistered())
    {
        qWarning() << "全局快捷键 Ctrl+Alt+S 注册失败！可能已被其他程序占用。";
    }

    // 网络管理器
    this->m_networkManager = new QNetworkAccessManager(this);

    // --- 初始状态 ---
    this->showLoading(false);

    // --- 定义并应用样式表 ---
    QString styleSheet = R"(
        #centralWidget {
            background-color: rgba(30, 33, 40, 0.9);
            border-radius: 12px;
        }
        #toolbar {
            background-color: rgba(45, 48, 56, 0.95);
            border-top-left-radius: 12px;
            border-top-right-radius: 12px;
            border-bottom: 1px solid #3a3d46;
        }
        #toolbarButton {
            background-color: transparent;
            color: #d0d0d0;
            border: none;
            padding: 8px 12px; /* 改为0，因为我们用内部布局来控制边距 */
            font-size: 14px;
        }
        #toolbarButton:hover {
            background-color: rgba(255, 255, 255, 0.1);
            border-radius: 6px;
        }
    )";
    setStyleSheet(styleSheet);

    // --- 信号槽连接 ---
    connect(this->m_newChatButton, &QPushButton::clicked, this, &TranslatorAgentWindow::startNewConversation);
    connect(this->m_screenshotButton,&QPushButton::clicked,this,&TranslatorAgentWindow::onScreenshotInitiated);
    connect(this->m_hotkey,&QHotkey::activated,this,&TranslatorAgentWindow::onScreenshotInitiated);
    connect(this->m_contentView, &QWebEngineView::loadFinished, this, [this](bool ok)
            {
        if (ok) {
            // 定义滚动条的CSS样式
            QString css = R"(
                ::-webkit-scrollbar {
                    width: 8px;
                    height: 8px;
                }
                ::-webkit-scrollbar-track {
                    background: transparent;
                }
                ::-webkit-scrollbar-thumb {
                    background: #555;
                    border-radius: 4px;
                }
                ::-webkit-scrollbar-thumb:hover {
                    background: #777;
                }
            )";

            // 将CSS注入到页面中
            QString script = QString(R"(
                var style = document.createElement('style');
                style.type = 'text/css';
                style.innerHTML = `%1`;
                document.head.appendChild(style);
            )").arg(css.replace("\n", ""));

            this->m_contentView->page()->runJavaScript(script);
        }
    });
    connect(m_pinButton, &QPushButton::clicked, this, &TranslatorAgentWindow::onPinButtonClicked);
    connect(m_networkManager,&QNetworkAccessManager::finished,this,&TranslatorAgentWindow::onOcrRequestFinished);
    connect(m_aiSocket, &QTcpSocket::connected, this, &TranslatorAgentWindow::onAiSocketConnected);
    connect(m_aiSocket, &QTcpSocket::disconnected, this, &TranslatorAgentWindow::onAiSocketDisconnected);
    connect(m_aiSocket, &QTcpSocket::readyRead, this, &TranslatorAgentWindow::onAiSocketReadyRead);

    // --- 初始化 SizeGrip ---
    m_sizeGrip = new QSizeGrip(this);
    // 设置为透明，或者根据需要设置样式
    m_sizeGrip->setStyleSheet("background-color: transparent;"); 
    m_sizeGrip->resize(20, 20); // 设置合适的大小
    m_sizeGrip->raise(); // 确保在最上层

    // --- 安装事件过滤器以处理工具栏的拖动 ---
    m_toolbar->installEventFilter(this);

}

// 点击事件
void TranslatorAgentWindow::mousePressEvent(QMouseEvent* event)
{
    if(event->button() == Qt::LeftButton)
    {
        if (windowHandle() && windowHandle()->startSystemMove()) {
             event->accept();
             return;
        }
        this->m_dragPos = event->globalPosition().toPoint() - this->frameGeometry().topLeft();
        event->accept();
    }
    return ;
}

// 移动事件
void TranslatorAgentWindow::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons() & Qt::LeftButton)
    {
        this->move(event->globalPosition().toPoint() - m_dragPos);
    }
    event->accept();
}

void TranslatorAgentWindow::showEvent(QShowEvent* event)
{
    if(this->m_centralWidget != nullptr) this->m_centralWidget->setMouseTracking(true);
    return ;
}

//在右下角调整大小的方块
void TranslatorAgentWindow::resizeEvent(QResizeEvent *event)
{
    QMainWindow::resizeEvent(event);
    // 保持 SizeGrip 在右下角
    if (m_sizeGrip) {
        int x = width() - m_sizeGrip->width();
        int y = height() - m_sizeGrip->height();
        m_sizeGrip->move(x, y);
        m_sizeGrip->raise();
    }
}

bool TranslatorAgentWindow::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == m_toolbar)
    {
        if (event->type() == QEvent::MouseButtonPress)
        {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
            if (mouseEvent->button() == Qt::LeftButton)
            {
                if (windowHandle() && windowHandle()->startSystemMove()) {
                    return true;
                }
                m_dragPos = mouseEvent->globalPosition().toPoint() - this->frameGeometry().topLeft();
                return false; // 让事件继续传播
            }
        }
        else if (event->type() == QEvent::MouseMove)
        {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
            if (mouseEvent->buttons() & Qt::LeftButton)
            {
                this->move(mouseEvent->globalPosition().toPoint() - m_dragPos);
                return false; // 让事件继续传播
            }
        }
    }
    return QMainWindow::eventFilter(watched, event);
}



void TranslatorAgentWindow::showLoading(bool show)
{
    if(show == true)
    {
        this->m_stackedWidget->setCurrentWidget(this->m_loadingWidget);
        this->m_loadingWidget->start();
    }
    else
    {
        this->m_stackedWidget->setCurrentWidget(this->m_contentView);
        this->m_loadingWidget->stop();
    }
    return ;
}

void TranslatorAgentWindow::startNewConversation()
{
    qDebug() << "“新对话”按钮被点击...";
    QString html = "<h3 style='color: #ccc; text-align: center;'>新对话已开启，请开始截图翻译...</h3>";

    m_contentView->setUrl(QUrl("about:blank"));         //先清空

    QTimer::singleShot(500,this,[this,html]
    {
        showLoading(true);
        QTimer::singleShot(1500,this,[this,html]()
        {
            updateContent(html);
            showLoading(false);
        });
    });
    return ;
}

void TranslatorAgentWindow::onScreenshotInitiated()
{
    qDebug() << "截图已启动...";

    // 1. 隐藏主窗口，为全屏截图做准备
    this->hide();

    // 2. 延时一小段时间（比如 150 毫秒）
    //    这是为了确保主窗口的隐藏动画完全结束后，再进行屏幕捕捉，
    //    避免把主窗口自己也截进去。
    QTimer::singleShot(150, this, [this]()
    {
        // 3. 创建并显示我们的截图覆盖层
        ScreenshotOverlay *overlay = new ScreenshotOverlay();

        // 4. 【关键】连接截图完成的信号
        //    当 overlay 发射 screenshotTaken 信号时，调用我们的 onScreenshotFinished 槽函数
        connect(overlay, &ScreenshotOverlay::screenshotTaken, this, &TranslatorAgentWindow::onScreenshotFinished);

        // 5. 【关键】处理用户取消截图的情况
        //    当 overlay 被销毁时（无论是成功还是按ESC取消），检查主窗口是否可见。
        //    如果不可见，说明是用户按了ESC取消了，这时需要重新把主窗口显示出来。
        connect(overlay, &QObject::destroyed, this, [this]()
        {
            if (!this->isVisible())
            {
                this->show();
            }
        });
    });
}

void TranslatorAgentWindow::onScreenshotFinished(const QPixmap &pixmap)
{
    qDebug() << "截图成功！图片尺寸:" << pixmap.size();
    m_contentView->setUrl(QUrl("about:blank"));

    //防止闪烁
    QTimer::singleShot(200,this,[this,pixmap]()
                       {
                           this->show();

                           showLoading(true);

                           QByteArray imageData;
                           QBuffer buffer(&imageData);
                           buffer.open(QIODevice::WriteOnly);
                           pixmap.save(&buffer, "PNG");

                           QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);

                           QHttpPart imagePart;
                           imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"image\"; filename=\"screenshot.png\""));
                           imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/png"));
                           imagePart.setBody(imageData);

                           multiPart->append(imagePart);

                           auto createTextPart = [](const QString &name, const QString &value) {
                               QHttpPart textPart;
                               textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"" + name + "\""));
                               textPart.setBody(value.toUtf8());
                               return textPart;
                           };

                           // 根据 Python 示例添加所有 data 字段
                           multiPart->append(createTextPart("file_type", "page"));
                           multiPart->append(createTextPart("resized_shape", "768"));
                           multiPart->append(createTextPart("embed_sep", " $,$ "));
                           multiPart->append(createTextPart("isolated_sep", "$$\n, \n$$"));

                           //    确保这里的端口号 (8503) 与您启动 p2t serve 时指定的端口号一致
                           QUrl url("http://127.0.0.1:8503/pix2text");
                           QNetworkRequest request(url);

                           QNetworkReply *reply = m_networkManager->post(request, multiPart);

                           // 将 multiPart 的父对象设置为 reply，这样当网络请求结束后，
                           // Qt 会自动帮我们清理 multiPart 占用的内存，避免内存泄漏。
                           multiPart->setParent(reply);
    });

    return ;
}

void TranslatorAgentWindow::updateContent(const QString &html)
{
    m_contentView->setHtml(html);
    return ;
}

void TranslatorAgentWindow::updatePinStatus()
{
    // 获取当前的窗口标志位
    Qt::WindowFlags flags = windowFlags();

    if (m_isPinned)
    {
        // 如果是置顶状态
        m_pinButton->setText("取消置顶");
        m_pinButton->setToolTip("取消置顶");
        // 在现有标志位的基础上，添加“始终置顶”的标志
        flags |= Qt::WindowStaysOnTopHint;
    } else
    {
        // 如果是取消置顶状态
        m_pinButton->setText("窗口置顶");
        m_pinButton->setToolTip("窗口置顶");
        // 在现有标志位的基础上，移除“始终置顶”的标志
        flags &= ~Qt::WindowStaysOnTopHint;
    }

    // 将修改后的标志位重新设置给窗口
    // 注意：setWindowFlags会暂时隐藏窗口，所以需要再次show()
    // 为了避免闪烁，我们只在窗口可见时这样做
    if (isVisible())
    {
        setWindowFlags(flags);
        show();
    } else
    {
        setWindowFlags(flags);
    }
    return ;
}

void TranslatorAgentWindow::onPinButtonClicked()
{
    // 切换置顶状态
    m_isPinned = !m_isPinned;
    // 调用辅助函数来应用新的状态
    updatePinStatus();
}

void TranslatorAgentWindow::onOcrRequestFinished(QNetworkReply *reply)
{
    // 首先，检查网络请求本身是否出错（比如连接失败、超时等）
    if (reply->error() != QNetworkReply::NoError)
    {
        qDebug() << "OCR 网络请求失败:" << reply->errorString();
        // 更新UI以显示错误信息
        QString errorHtml = QString("<div style='padding: 15px; color: #f77;'>"
                                    "<h3>OCR 服务连接失败</h3>"
                                    "<p>错误: %1</p>"
                                    "<p>请确认 Pix2Text 服务已在本地正确运行。</p>"
                                    "</div>").arg(reply->errorString());
        // 我们不再调用 updateContent，而是直接设置内容并隐藏加载
        showLoading(false);
        updateContent(errorHtml);

        reply->deleteLater(); // 清理网络应答对象
        return;
    }

    // 读取服务器返回的所有数据
    QByteArray responseData = reply->readAll();

    // 将返回的字节数据解析为 JSON 文档
    QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData);

    // 检查JSON是否有效且是一个对象
    if (!jsonDoc.isObject())
    {
        qDebug() << "OCR 返回了无效的JSON格式";
        showLoading(false);
        updateContent("<h3 style='color: #f77;'>OCR 服务返回数据格式错误！</h3>");
        reply->deleteLater();
        return;
    }

    qDebug() << "成功接收到OCR结果:" << QString::fromUtf8(responseData);


    // 打包数据
    QJsonObject requestObj;
    requestObj["type"] = "translate";
    requestObj["data"] = QJsonDocument::fromJson(responseData).object()["results"].toString();

    QJsonDocument requestDoc(requestObj);
    QByteArray requestData = requestDoc.toJson(QJsonDocument::Compact) + "\n"; // 加上换行符

    // 检查socket是否连接
    if (m_aiSocket->state() == QAbstractSocket::ConnectedState)
    {
        qDebug() << "已连接到AI服务，正在发送OCR数据...";
        m_currentMarkdown.clear(); // 清空上次的结果
        m_aiSocket->write(requestData);

    }
    else
    {
        qDebug() << "错误：未连接到AI服务！无法发送数据。";
        showLoading(false);
        updateContent("<h3 style='color: #f77;'>AI服务未连接！</h3>");
    }


    // 清理本次网络应答对象
    reply->deleteLater();
    return ;
}


void TranslatorAgentWindow::onAiSocketConnected()
{
    qDebug() << "成功连接到AI服务！";
}

void TranslatorAgentWindow::onAiSocketDisconnected()
{
    qDebug() << "与AI服务的连接已断开。正在尝试重连...";

    QTimer::singleShot(3000, this, [this](){
        m_aiSocket->connectToHost("127.0.0.1", 8504);
    });
}

void TranslatorAgentWindow::onAiSocketReadyRead()
{
    showLoading(false);
    QByteArray incomingData = m_aiSocket->readAll();
    m_currentMarkdown.append(QString::fromUtf8(incomingData));

    qDebug() << "收到AI数据片段:" << QString::fromUtf8(incomingData);
    updateContent(m_currentMarkdown);
}

TranslatorAgentWindow::~TranslatorAgentWindow()
{
    if (m_p2tProcess->state() == QProcess::Running)
    {
        qDebug() << "正在关闭后台OCR服务...";
        m_p2tProcess->kill(); // 强制终止进程
        if (!m_p2tProcess->waitForFinished(5000))
        { // 等待最多5秒
            qDebug() << "关闭后台服务超时。";
        }
        else
        {
            qDebug() << "后台服务已成功关闭。";
        }
    }
}
